<template>
  <Page title="短文朗读">
    <template #navBarCustom>
      <div class="flex items-center navBox">
        <div class="back" @click="back">
          <img class="icon" src="static/icons/back.png" mode="" />
          <span style="color: #fff">短文朗读</span>
        </div>
      </div>
    </template>
    <template #content>
      <div class="w-full h-full p-20px box-border">
        <div
          class="container w-full h-full p-20px box-border overflow-hidden bg-white flex flex-col"
        >
          <div class="w-full h-full overflow-scroll">
            <!-- 概况 -->
            <div class="overview text-center">
              <div class="text-333 font-normal">
                <span>总得分：</span>
                <span
                  class="font-semibold"
                  :class="`text-${getScoreClass(score / totalScore)}`"
                  style="font-size: 0.5rem; line-height: 0.7rem"
                  >{{ score }}</span
                >
                <span :class="`text-${getScoreClass(score / totalScore)}`">分</span>
                <span>/{{ totalScore }}分</span>
              </div>
            </div>
            <!-- 详情 -->
            <div class="questions-wrap mt-10px">
              <div v-for="(i, index) in questions" :key="i.questionId" class="item">
                <div class="score text-333 flex justify-between items-center px-64px box-border">
                  <span>准确度：{{ i.pronunciation }} 分</span>
                  <span>流畅度：{{ i.fluency }}分</span>
                  <span>完整度：{{ i.integrity }}分</span>
                </div>
                <div class="play flex justify-between">
                  <div class="play-btn item flex-center box-border">
                    <img
                      style="margin-right: 0.06rem"
                      src="static/icons/speaker.png"
                      alt=""
                      srcset=""
                      :data-audio-src="i.stemAudio"
                    />
                    <span>原音</span>
                  </div>
                  <div class="play-btn item flex-center box-border">
                    <img
                      style="margin-right: 0.06rem"
                      src="static/icons/my-records.png"
                      alt=""
                      srcset=""
                      :data-audio-src="i.selfAudio"
                    />
                    <span>录音</span>
                  </div>
                </div>
                <div style="font-size: 0.26rem" v-html="i.stem.html"></div>
                <div class="hr my-30px"></div>
                <div class="" style="font-size: 18px; color: #333333">
                  <div>准确度：朗读发音的准确程度，如单词发音、重音、重读等。 </div>
                  <div>流畅度：朗读的流畅程度，如停顿、语调、节奏等。</div>
                  <div>完整度：朗读内容的完整程度，如是否漏读、乱读。</div>
                  <div class="mt-20px">根据发音得分文本会展示不同颜色</div>
                  <div class="rules mt-6px flex">
                    <div class="text-30C9A1 text-center mr-10px">
                      <div>Nothing is</div>
                      <span class="arrow bg-30C9A1 my-10px inline-block"></span>
                      <div>发音很棒</div>
                    </div>
                    <div class="text-F8AC23 text-center mr-10px">
                      <div>impossible</div>
                      <span class="arrow bg-F8AC23 my-10px inline-block"></span>
                      <div>发音良好</div>
                    </div>
                    <div class="text-FF4040 text-center">
                      <div>to a willing heart.</div>
                      <span class="arrow bg-FF4040 my-10px inline-block"></span>
                      <div>发音较差/漏读</div>
                    </div>
                  </div>
                </div>
                <div class="hr my-30px" v-show="index < questions.length - 1"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </Page>
</template>

<script>
import Page from '@/components/page/newPage'
import { mapState } from 'vuex'
import { formatQuestionStem } from '@/utils/question'
import Mixin from '../mixin'

export default {
  components: {
    Page
  },
  mixins: [Mixin],
  inject: ['_addTagClickHandler', '_removeTagClickHandler'],
  data() {
    return {}
  },
  computed: {
    ...mapState(['homework']),
    questions() {
      const { questions } = this.homework.currentHomework

      return questions
        .map((q) => {
          if (q.stem.structure_type === 'collector.read') {
            const { questionId, stem, answer, remoteStudentAnswer = {} } = q
            const { studentScore, questionScore, studentAnswer } = remoteStudentAnswer
            const {
              info: { value = '', audio = '' }
            } = stem
            let html = `<span class="text-FF4040">${value}</span>`
            let selfAudio = ''
            let pronunciation = 0,
              fluency = 0,
              integrity = 0

            try {
              const { anSqs } = studentAnswer
              const { anStudentUrl = '', yzsRes = '' } = anSqs[0].ans[0]
              const { lines } = JSON.parse(yzsRes)
              const {
                pronunciation: _pronunciation,
                fluency: _fluency,
                integrity: _integrity,
                words
              } = lines[0]

              pronunciation = parseInt(_pronunciation)
              fluency = parseInt(_fluency)
              integrity = parseInt(_integrity)
              selfAudio = anStudentUrl
              html = `<span>${value
                .replace(/<[^>]+>/g, '')
                .replace('.', '')
                .split(' ')
                .map((word) => {
                  const yzsWordItem = words.find((w) => w.text.toLowerCase() === word.toLowerCase())
                  if (yzsWordItem) {
                    const { score } = yzsWordItem
                    if (score < 4) {
                      return `<span class="text-FF4040">${word}</span>`
                    } else if (score >= 4 && score < 8) {
                      return `<span class="text-F8AC23">${word}</span>`
                    } else {
                      return `<span class="text-30C9A1">${word}</span>`
                    }
                  } else {
                    return `<span class="text-FF4040">${word}</span>`
                  }
                })
                .join(' ')}<span>`
            } catch (error) {}

            return {
              questionId,
              stem: formatQuestionStem({
                html,
                og: null,
                sqs: [],
                type: '英语听说-短文朗读'
              }),
              pronunciation,
              fluency,
              integrity,
              stemAudio: audio,
              selfAudio,
              answer,
              studentAnswer,
              studentScore,
              questionScore
            }
          } else {
            return null
          }
        })
        .filter((q) => !!q)
    },
    score() {
      let score = 0
      this.questions.forEach((q) => {
        const { studentScore } = q
        score += studentScore
      })

      return score
    },
    totalScore() {
      let totalScore = 0
      this.questions.forEach((q) => {
        const { questionScore } = q
        totalScore += questionScore
      })

      return totalScore
    }
  },
  mounted() {
    this._addTagClickHandler('span', this.handleSpanClick)
    this._addTagClickHandler('img', this.handleImgClick)
    this._addTagClickHandler('div', this.handleDivClick)
    console.log(this.questions)
  },
  beforeDestroy() {
    this._removeTagClickHandler('span', this.handleSpanClick)
    this._removeTagClickHandler('img', this.handleImgClick)
    this._removeTagClickHandler('div', this.handleDivClick)
  },
  methods: {
    back() {
      this.$router.back()
    },
    handleSpanClick(node) {
      const parentNode = node.parentElement.children[0]

      if (parentNode && parentNode.tagName === 'IMG') {
        const { currentSrc = '' } = parentNode
        if (currentSrc.indexOf('speaker.png') != -1 || currentSrc.indexOf('my-records.png') != -1) {
          const { audioSrc } = parentNode.dataset

          if (!audioSrc || audioSrc === 'undefined') {
            currentSrc.indexOf('my-records.png') != -1 && this.$message.error('未作答')
            return
          }

          this.playAudio(parentNode, audioSrc)
        }
      }
    },
    handleImgClick(node) {
      const { currentSrc = '' } = node
      if (currentSrc.indexOf('speaker.png') != -1 || currentSrc.indexOf('my-records.png') != -1) {
        const { audioSrc } = node.dataset

        if (!audioSrc || audioSrc === 'undefined') {
          currentSrc.indexOf('my-records.png') != -1 && this.$message.error('未作答')
          return
        }

        this.playAudio(node, audioSrc)
      }
    },
    handleDivClick(node) {
      if (node.className.indexOf('play-btn') != -1) {
        const imgNode = node.children[0]
        const { audioSrc } = imgNode.dataset

        if (!audioSrc || audioSrc === 'undefined') {
          currentSrc.indexOf('my-records.png') != -1 && this.$message.error('未作答')
          return
        }

        this.playAudio(imgNode, audioSrc)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.navBox {
  padding: 0 20px;
  box-sizing: border-box;
}
.back {
  height: 100%;
  display: flex;
  align-items: center;
  font-size: 28px;

  .icon {
    width: 17.14px;
    height: 30px;
    margin-right: 11px;
  }
}
.container {
  border-radius: 16px;

  .overview {
    font-size: 20px;
  }

  .questions-wrap {
    .item {
      .score {
        width:937px;
        height:93px;
        font-size: 26px;
        font-weight: 400;
        background-color: #edf9ff;
        margin: 0 auto;
      }

      .play {
        width: 350px;
        margin: 20px auto;

        .item {
          width: 140px;
          height:60px;
          border-radius: 30px;
          border: 2px solid #51c3ff;
          font-size: 26px;
          font-weight: 400;
          color: #51c3ff;

          img {
            width: 40px;
            height: 40px;
          }

          .playing {
            @keyframes play {
              0% {
                opacity: 0.5;
              }

              25% {
                opacity: 0.25;
              }

              50% {
                opacity: 0.5;
              }

              75% {
                opacity: 0.75;
              }

              100% {
                opacity: 1;
              }
            }

            animation: play 1s ease-in-out infinite backwards;
          }
        }
      }

      .rules {
        .arrow {
          width: 1px;
          height: 24px;
        }
      }

      .hr {
        height: 1px;
        background: #eee;
      }
    }
  }
}
</style>
